const cabinetsGrpRespositories = require("../repositories/cabinetsgrpRepositories");

class CabinetGrpServices {
  // 统一响应函数
  handleResponse(data, error, notFoundMessage = "实体未找到") {
    if (error) {
      return {
        code: 1,
        msg: error.message,
        statusCode: error.statusCode || 500,
      };
    }
    if (!data) {
      return {
        code: 1,
        msg: notFoundMessage,
        statusCode: 404,
      };
    }
    return { code: 0, data: data };
  }

  async addNewCabinetsGrp(cabinetsGrpData) {
    const { name } = cabinetsGrpData;
    const hasCabinetsGrp = await cabinetsGrpRespositories.getCabinetsGrpByName(
      name
    );
    if (hasCabinetsGrp) {
      return {
        code: 1,
        msg: "柜子分组已存在",
        statusCode: 400,
      };
    }
    const cabinetsGrp = await cabinetsGrpRespositories.addNewCabinetsGrp(
      cabinetsGrpData
    );
    return cabinetsGrp
      ? this.handleResponse(cabinetsGrp, null)
      : this.handleResponse(null, null, "添加失败");
  }

  async delCabinetsGrpById(id) {
    const bool = await cabinetsGrpRespositories.delCabinetsGrpById(id);
    return bool
      ? this.handleResponse("删除成功", null, null)
      : this.handleResponse(null, null, "删除失败");
  }

  async updateCabinetsGrpById(id, cabinetsGrpData) {
    const cabinetsGrp = await cabinetsGrpRespositories.getCabinetsGrpById(id);
    if (!cabinetsGrp) {
      return this.handleResponse(null, null, "目标柜子分组不存在");
    }
    const bool = await cabinetsGrpRespositories.updateCabinetsGrpById(
      id,
      cabinetsGrpData
    );
    return bool
      ? this.handleResponse("更新成功", null, null)
      : this.handleResponse(null, null, "更新失败");
  }

  async getCabinetsGrpById(id) {
    const cabinetsGrp = await cabinetsGrpRespositories.getCabinetsGrpById(id);
    return this.handleResponse(cabinetsGrp, null, null);
  }

  async getAllCabinetsGrps() {
    const cabinetsGrps = await cabinetsGrpRespositories.getAllCabinetsGrps();
    return this.handleResponse(cabinetsGrps);
  }

  async getMapofCabinetsGrps() {
    const cabinetsGrps = await cabinetsGrpRespositories.getMapofCabinetsGrps();
    return this.handleResponse(cabinetsGrps, null, "未找到柜子分组");
  }
}

module.exports = new CabinetGrpServices();
